import { baseUrlDev, baseUrlPro } from '@src/const';
import { isProd } from '@src/const/env';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

export interface CommonResponse {
  msg: string;
  code: number;
  data: any;
  x_trace_id?: string;
  message?: string;
  message_cn?: string;
  originalRes?: AxiosResponse;
  [propName: string]: any;
}

// 自定义请求
const axiosInstance = axios.create({
  baseURL: isProd ? baseUrlPro : baseUrlDev, // 根据环境变量设置baseURL
  timeout: 5000, // 超时时间
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token') || '';
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; // 在请求头中添加token信息
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  },
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // const { data } = response;
    // 在此处处理响应数据，并进行日志上报等操作
    return response;
  },
  (error) => {
    console.error('响应错误：', error);
    return Promise.reject(error);
  },
);

// 封装请求
const request = (params: AxiosRequestConfig): Promise<any> => {
  return new Promise((resolve, reject) => {
    axiosInstance(params)
      .then((res: AxiosResponse<CommonResponse>) => {
        const {
          data: { code, data, msg },
        } = res;

        // 返回码不为0就报错
        if (code) {
          reject({
            msg,
          });
        }
        resolve(data);
      })
      .catch(() => {
        reject({
          msg: '系统出小差了，请重试',
        });
      });
  });
};

export default request;
